<template>
  <div>
    <button @click="exportExcel">导出 Excel</button>
  </div>
</template>

<script>
export default {
  methods: {
    async exportExcel() {
      // 动态导入 exceljs，避免打包过大
      const ExcelJS = await import('exceljs');

      // 创建工作簿和工作表
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet 1');

      // 设置列头
      worksheet.columns = [
        { header: '姓名', key: 'name', width: 20 },
        { header: '年龄', key: 'age', width: 10 },
        { header: '邮箱', key: 'email', width: 30 }
      ];

      // 数据
      const data = [
        { name: 'Alice', age: 25, email: 'alice@example.com' },
        { name: 'Bob', age: 30, email: 'bob@example.com' },
        { name: 'Charlie', age: 35, email: 'charlie@example.com' }
      ];

      worksheet.addRows(data);

      // 导出 Excel 文件
      const buffer = await workbook.xlsx.writeBuffer();
      const blob = new Blob([buffer], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'example.xlsx';
      link.click();
      URL.revokeObjectURL(link.href); // 释放内存
    }
  }
}
</script>
